<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="bizOrgNo"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
                @changeSelect="companyChange"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="产品">
              <FilterSelect2
                v-model="form.productId"
                :optionlist="productList"
                :valuekey="{ name: 'name', value: 'id' }"
                placeholder="请选择产品"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="14" style="text-align: right">
            <el-form-item>
              <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="titlebox">
        <div class="text"></div>
        <div style="flex: 1; text-align: right; margin-right: 10px">
          <el-button type="primary" size="small" @click="add('add')"
            ><i class="el-icon-plus">新增</i></el-button
          >
        </div>
        <TopTile
          @command="command"
          @daochu="daochu"
          @shuaxin="shuaxin"
        ></TopTile>
      </div>
      <div class="table-content">
        <template>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            border
            id="exportTabyong"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center'
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              align="center"
              label="序号"
              width="80"
            >
            </el-table-column>
            <el-table-column prop="companyName" label="用电企业">
            </el-table-column>
            <el-table-column prop="productName" label="产品" min-width="60">
            </el-table-column>
            <el-table-column prop="teamCode" label="班组编码" min-width="80">
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" min-width="60">
            </el-table-column>
            <el-table-column prop="teamName" label="班组" min-width="60">
            </el-table-column>
            <el-table-column
              prop="energyPercent"
              label="能耗占比"
              min-width="40"
            >
              <template slot-scope="scope">
                {{
                  scope.row.energyPercent ? scope.row.energyPercent + '%' : '-'
                }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <div class="operate">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="编辑"
                    placement="top"
                  >
                    <i
                      style="
                        font-size: 14px;
                        color: rgb(64, 149, 229);
                        cursor: pointer;
                      "
                      class="el-icon-edit"
                      @click="handleEdit(scope.row)"
                    ></i
                  ></el-tooltip>
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除"
                    placement="top"
                  >
                    <i
                      style="font-size: 14px; color: red; cursor: pointer"
                      class="el-icon-delete"
                      @click="handleDel(scope.row)"
                    ></i
                  ></el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div class="fenye">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page.sync="pageobj._pageNo"
            @current-change="currentChange"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <div class="dialog">
      <div class="dialog">
        <el-dialog
          :title="isEdit === 'add' ? '新增班组分摊' : '修改班组分摊'"
          :visible.sync="DialogVisible"
          v-if="DialogVisible"
          label-position="left"
          width="500px"
          :destroy-on-close="true"
          :close-on-click-modal="false"
          :before-close="beforeClose"
        >
          <el-form
            :rules="rules"
            ref="form"
            :model="dialogForm"
            label-width="100px"
          >
            <el-form-item label="企业名称" prop="companyId">
              <FilterSelect2
                size="small"
                v-model="dialogForm.companyId"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
                @changeSelect="onDialogCompanyChange"
              ></FilterSelect2>
            </el-form-item>
            <el-form-item label="产品" prop="productId">
              <FilterSelect2
                size="small"
                v-model="dialogForm.productId"
                :optionlist="dialogProductList"
                :valuekey="{ name: 'name', value: 'id' }"
                placeholder="请选择产品"
              ></FilterSelect2>
            </el-form-item>
            <el-form-item label="部门" prop="departmentId">
              <FilterSelect2
                size="small"
                v-model="dialogForm.departmentId"
                :optionlist="departmentList"
                :valuekey="{ name: 'departmentName', value: 'departmentId' }"
                placeholder="请选择部门"
                @changeSelect="onDepartmentChange"
              ></FilterSelect2>
            </el-form-item>
            <el-form-item label="班组" prop="teamId">
              <FilterSelect2
                size="small"
                v-model="dialogForm.teamId"
                :optionlist="currentTeamList"
                :valuekey="{ name: 'teamName', value: 'teamId' }"
                placeholder="请选择班组"
                :disabled="!dialogForm.departmentId"
              ></FilterSelect2>
            </el-form-item>
            <el-form-item label="能耗占比" prop="energyRatio">
              <el-input
                size="small"
                v-model="dialogForm.energyRatio"
                placeholder="请输入能耗占比"
                @input="handleEnergyRatioInput"
              >
                <span slot="suffix">%</span>
              </el-input>
            </el-form-item>
          </el-form>
          <div style="margin-top: 10px; text-align: center">
            <span slot="footer" class="dialog-footer">
              <el-button @click="beforeClose">取 消</el-button>
              <el-button type="primary" @click="submit">保 存</el-button>
            </span>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { getCompanyListApi } from '@/api/Configuration-management/index'
import {
  getTeamAllocationPageApi,
  addTeamAllocationApi,
  updateTeamAllocationApi,
  deleteTeamAllocationApi,
  getProductListApi,
  getDepartmentTeamListApi
} from '@/api/energy-consumption/factory-energy/team-allocation'
import { exportexcel } from '@/utils/excel'
import FilterSelect2 from '@/components/FilterSelect2/index.vue'
import TopTile from '@/components/TopTitle/index.vue'
import Twobtn from '@/components/Twobtn/index.vue'

export default {
  name: 'TeamAllocation',
  components: {
    FilterSelect2,
    TopTile,
    Twobtn
  },
  data() {
    return {
      dataList: [],
      enterpriseCode: '',
      id: '',
      bizOrgNo: '',
      isEdit: 'add',
      dizhi: '',
      DialogVisible: false,
      form: {
        productId: ''
      },
      rules: {
        companyId: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        productId: [
          { required: true, message: '请选择产品', trigger: 'change' }
        ],
        departmentId: [
          { required: true, message: '请选择所属部门', trigger: 'change' }
        ],
        teamId: [{ required: true, message: '请选择班组', trigger: 'change' }],
        energyRatio: [
          { required: true, message: '请输入能耗占比', trigger: 'blur' }
        ]
      },
      statusList: [],
      dialogForm: {},
      address: '',
      isshow: false,
      isheight: 72,
      date: [],
      iissize: 'medium',
      loading: false,
      tableData: [],
      total: 0,
      pageobj: {
        _pageNo: 0,
        _pageSize: 10
      },
      progress: 1,
      addType: '',
      companyData: {},
      companyList: [],
      departmentList: [], // 部门列表
      productList: [], // 产品列表
      dialogProductList: [], // 弹窗中的产品列表
      currentTeamList: [] // 当前部门下的班组列表
    }
  },

  async mounted() {
    await this.getCompanyList()
    await this.getProductList()
    await this.getdatalist()
  },
  methods: {
    async companyChange(val) {
      if (val) {
        localStorage.setItem('companyId', val)
        // 切换企业时只重新获取产品列表
        await this.getProductList()
        // 清空产品选择
        this.form.productId = ''
      }
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi({ companyId: this.bizOrgNo })
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find((i) => i.id == companyId)) {
        this.bizOrgNo = companyId
      } else {
        this.bizOrgNo = this.companyList[0].id
      }
    },
    // 获取部门及班组列表
    async getDepartmentTeamList() {
      try {
        const res = await getDepartmentTeamListApi({
          companyId: this.bizOrgNo
        })
        if (res.code === 200) {
          this.departmentList = res.data.list || []
        }
      } catch (error) {
        console.error('获取部门班组列表失败:', error)
        this.departmentList = []
      }
    },
    // 获取弹窗中的部门及班组列表
    async getDialogDepartmentTeamList(companyId) {
      try {
        const res = await getDepartmentTeamListApi({
          companyId: companyId
        })
        if (res.code === 200) {
          this.departmentList = res.data.list || []
        }
      } catch (error) {
        console.error('获取弹窗部门班组列表失败:', error)
        this.departmentList = []
      }
    },
    // 获取产品列表
    async getProductList() {
      try {
        const res = await getProductListApi({
          companyId: this.bizOrgNo
        })
        if (res.code === 200) {
          this.productList = res.data.list || []
        }
      } catch (error) {
        console.error('获取产品列表失败:', error)
        this.productList = []
      }
    },
    // 获取弹窗中的产品列表
    async getDialogProductList(companyId) {
      try {
        const res = await getProductListApi({
          companyId: companyId
        })
        if (res.code === 200) {
          this.dialogProductList = res.data.list || []
        }
      } catch (error) {
        console.error('获取弹窗产品列表失败:', error)
        this.dialogProductList = []
      }
    },
    // 初始化
    async getchushihua() {
      this.bizOrgNo = this.companyList[0].id
    },
    // 获取数据
    async getdatalist() {
      this.loading = true
      try {
        const res = await getTeamAllocationPageApi({
          companyId: this.bizOrgNo,
          productId: this.form.productId,
          pageNo: this.pageobj._pageNo - 1,
          pageSize: this.pageobj._pageSize
        })
        if (res.code === 200) {
          this.tableData = res.data.list || []
          this.total = res.data.totalCount || 0
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.tableData = []
        this.total = 0
      }
      this.loading = false
    },
    // 分页查询
    currentChange() {
      this.getdatalist()
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist('')
      this.$message({
        type: 'success',
        message: '列表刷新成功',
        duration: 2000
      })
    },
    chaxun() {
      this.getdatalist()
    },
    // 导出
    daochu() {
      exportexcel(
        '/ecm-microservice-biz/ecm/product/team/allocation/export',
        {
          companyId: this.bizOrgNo,
          productId: this.form.productId
        },
        '班组分摊'
      )
    },
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    async submit() {
      await this.$refs.form.validate()
      try {
        const data = {
          ...this.dialogForm,
          energyPercent: parseFloat(this.dialogForm.energyRatio) || 0
        }
        const res =
          this.isEdit === 'add'
            ? await addTeamAllocationApi(data)
            : await updateTeamAllocationApi(data)

        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: this.isEdit === 'add' ? '新增成功' : '修改成功',
            duration: 2000
          })
          this.getdatalist()
          this.beforeClose()
        } else {
          this.$message({
            type: 'error',
            message:
              res.message || (this.isEdit === 'add' ? '新增失败' : '修改失败'),
            duration: 2000
          })
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message({
          type: 'error',
          message: this.isEdit === 'add' ? '新增失败' : '修改失败',
          duration: 2000
        })
      }
    },
    async chongzhi() {
      await this.getchushihua()
      this.date = []
      this.enterpriseCode = ''
      this.dataList = []
      this.form.productId = ''
      this.getdatalist('')
      // 重新获取产品列表
      await this.getProductList()
    },
    // 编辑
    async handleEdit(row) {
      console.log(row)
      this.isEdit = 'edit'
      this.$set(this.dialogForm, 'companyId', row.companyId)
      this.$set(this.dialogForm, 'productId', row.productId)
      this.$set(this.dialogForm, 'departmentId', row.departmentId)
      this.$set(this.dialogForm, 'teamId', row.teamId)
      this.$set(this.dialogForm, 'energyRatio', row.energyPercent)
      this.$set(this.dialogForm, 'id', row.id)

      // 获取弹窗中对应企业的部门班组列表
      await this.getDialogDepartmentTeamList(row.companyId)

      // 获取弹窗中对应企业的产品列表
      await this.getDialogProductList(row.companyId)

      // 设置当前部门下的班组列表
      this.setCurrentTeamList(row.departmentId)

      this.DialogVisible = true
    },
    async add(type) {
      this.isEdit = type
      const defaultCompanyId = this.companyList[0].id
      this.$set(this.dialogForm, 'companyId', defaultCompanyId)
      this.$set(this.dialogForm, 'energyRatio', '')

      // 获取弹窗中对应企业的部门班组列表
      await this.getDialogDepartmentTeamList(defaultCompanyId)

      // 设置默认部门
      this.$set(
        this.dialogForm,
        'departmentId',
        this.departmentList[0]?.departmentId || ''
      )

      // 获取弹窗中对应企业的产品列表
      await this.getDialogProductList(defaultCompanyId)

      // 默认选择第一个产品
      if (this.dialogProductList && this.dialogProductList.length > 0) {
        this.$set(this.dialogForm, 'productId', this.dialogProductList[0].id)
      } else {
        this.$set(this.dialogForm, 'productId', '')
      }

      // 设置当前部门下的班组列表
      this.setCurrentTeamList(this.dialogForm.departmentId)

      // 默认选择第一个班组
      if (this.currentTeamList && this.currentTeamList.length > 0) {
        this.$set(this.dialogForm, 'teamId', this.currentTeamList[0].teamId)
      } else {
        this.$set(this.dialogForm, 'teamId', '')
      }

      this.DialogVisible = true
    },
    next(progress, id) {
      this.progress = progress
      if (id) {
        this.id = id
      }
    },
    fileData(data) {
      this.companyData = data
      this.dizhi = data.companyAddress
    },
    beforeClose() {
      this.DialogVisible = false
      this.dialogForm = {}
      this.isEdit = 'add'
      this.currentTeamList = []
      this.dialogProductList = []
    },
    finish() {
      this.centerDialogVisible = false
      this.progress = 1
      this.id = ''
      this.getdatalist('')
    },
    // 删除
    async handleDel(item) {
      this.$confirm('此操作将永久删除该班组分摊记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          try {
            const res = await deleteTeamAllocationApi(item.id)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '删除成功',
                duration: 2000
              })
              this.getdatalist()
            } else {
              this.$message({
                type: 'error',
                message: res.message || '删除失败',
                duration: 2000
              })
            }
          } catch (error) {
            console.error('删除失败:', error)
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 2000
            })
          }
        })
        .catch((action) => {
          if (action === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          }
        })
    },
    // 弹窗中企业选择变化时，重新获取产品列表
    async onDialogCompanyChange(companyId) {
      if (companyId) {
        // 重新获取弹窗中的产品列表
        await this.getDialogProductList(companyId)
        // 重新获取弹窗中的部门班组列表
        await this.getDialogDepartmentTeamList(companyId)

        // 默认选择第一个产品
        if (this.dialogProductList && this.dialogProductList.length > 0) {
          this.$set(this.dialogForm, 'productId', this.dialogProductList[0].id)
        } else {
          this.$set(this.dialogForm, 'productId', '')
        }

        // 默认选择第一个部门
        if (this.departmentList && this.departmentList.length > 0) {
          this.$set(
            this.dialogForm,
            'departmentId',
            this.departmentList[0].departmentId
          )
        } else {
          this.$set(this.dialogForm, 'departmentId', '')
        }

        // 设置当前部门下的班组列表
        this.setCurrentTeamList(this.dialogForm.departmentId)

        // 默认选择第一个班组
        if (this.currentTeamList && this.currentTeamList.length > 0) {
          this.$set(this.dialogForm, 'teamId', this.currentTeamList[0].teamId)
        } else {
          this.$set(this.dialogForm, 'teamId', '')
        }
      }
    },
    // 部门选择变化时，更新班组列表
    onDepartmentChange(departmentId) {
      this.setCurrentTeamList(departmentId)
      // 默认选择该部门下的第一个班组
      if (this.currentTeamList && this.currentTeamList.length > 0) {
        this.$set(this.dialogForm, 'teamId', this.currentTeamList[0].teamId)
      } else {
        this.$set(this.dialogForm, 'teamId', '')
      }
    },
    // 设置当前部门下的班组列表
    setCurrentTeamList(departmentId) {
      if (!departmentId) {
        this.currentTeamList = []
        return
      }

      const department = this.departmentList.find(
        (dept) => dept.departmentId === departmentId
      )
      if (department && department.teamVOList) {
        this.currentTeamList = department.teamVOList
      } else {
        this.currentTeamList = []
      }
    },
    // 处理能耗占比输入
    handleEnergyRatioInput(value) {
      // 只允许数字和小数点
      let newValue = value.replace(/[^\d.]/g, '')

      // 不能以0开头（除了0.xx的情况）
      if (newValue.length > 1 && newValue[0] === '0' && newValue[1] !== '.') {
        newValue = newValue.substring(1)
      }

      // 只能有一个小数点
      const parts = newValue.split('.')
      if (parts.length > 2) {
        newValue = parts[0] + '.' + parts.slice(1).join('')
      }

      // 限制小数点后最多两位
      if (parts.length === 2 && parts[1].length > 2) {
        newValue = parts[0] + '.' + parts[1].substring(0, 2)
      }

      // 更新输入框的值
      this.$set(this.dialogForm, 'energyRatio', newValue)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
.option {
  height: auto;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.bigbox {
  background-color: #f1f1f1;
  padding: 10px;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
  }
  .bodybox {
    background-color: #fff;
    margin-top: 10px;
    padding: 20px 20px 20px 20px;
    height: 90%;
    .titlebox {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .text {
        font-weight: bold;
        font-size: 18px;
      }
      .right {
        align-items: center;
        i {
          margin-left: 10px;
        }
      }
    }
    .fenye {
      margin-top: 15px;
      text-align: right;
    }
  }
}

.operate {
  display: flex;
  justify-content: space-around;
}
.dialogBtn {
  width: 80px;
  height: 40px;
  border-radius: 4px;
  font-size: 14px;
  text-align: center;
  align-items: center;
}
::v-deep.dialog {
  .el-dialog {
    width: 800px;
    .el-dialog__header {
      padding: 20px 0;
      padding-left: 20px;
      font-size: 14px;
      text-align: left !important;
      border-bottom: 1px solid #f7f7f7;
    }
    .el-dialog__footer {
      margin-top: 50px;
      height: 60px;
    }
  }
}

::v-deep.el-date-editor {
  .el-range-separator {
    line-height: 22px;
  }
}

::v-deep.dialog-content {
  .el-form-item__error {
    margin-top: -8px;
  }
  .el-form-item {
    height: 50px;
    .el-form-item__content {
      width: 90%;
      .el-select {
        width: 100%;
      }
    }
    .el-form-item__label {
      padding: 0;
      padding-right: 10px;
      padding-top: 3px;
      line-height: 32px;
    }
    margin-bottom: 5px;
  }
}
::v-deep.checkbox-item {
  border-top: 1px solid #f7f7f7;
  border-bottom: 1px solid #f7f7f7;
  margin-top: 20px;
  padding: 20px 0;
  .el-form-item {
    .el-form-item__content {
      width: 750px;
    }
  }
  .el-checkbox-group {
    .el-checkbox {
      margin-right: 0;
    }
  }
  .yewufanwei {
    padding-top: 10px;
  }
}

.map {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 500px;
}
button {
  cursor: pointer;
}
.top-line {
  display: flex;
  width: 100%;
  height: 80px;
  padding-bottom: 20px;
  margin-bottom: 30px;
  justify-content: space-between;
  line-height: 30px;
  align-items: center;
  border-bottom: 1px solid #bbb;
  .line {
    width: 12%;
    height: 1px;
    border: 1px solid #e0e0e0;
    background: #bbb;
  }
  .top-item {
    display: flex;
    .circle {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      border: 1px solid #bbb;
      color: #bbb;
      text-align: center;
      line-height: 30px;
      margin-right: 10px;
    }
    .text {
      font-weight: 800;
    }
  }
}
.checked-bgc {
  background-color: #1684fc;
  color: #fff !important;
  border: 1px solid #1684fc !important;
}
</style>
